//
//  LoadingView.m
//  Unity-iPhone
//
//  Created by zhang fenglin on 13-10-10.
//
//

#import "LoadingView.h"

#define ANIMATION_DURATION 0.5
#define VIEW_ALPHA 0.6

@implementation LoadingView

- (id)init {
    self = [super init];
    if (self) {
        self.backgroundColor = [UIColor blackColor];
        self.alpha = 0;
        
        spinning = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
        spinning.frame = CGRectMake(0, 0, 50, 50);
        
        [spinning startAnimating];
        [self addSubview:spinning];
    }
    return self;
}

- (void)show {
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    [self showInView:window animated:YES];
}

- (void)showAnimated:(BOOL)animated {
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    [self showInView:window animated:animated];
}

- (void)showInView:(UIView *)view animated:(BOOL)animated {
    CGFloat width = view.frame.size.width;
    CGFloat height = view.frame.size.height;
    self.frame = CGRectMake(0, 0, width, height);
    self.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    [view addSubview:self];
    
    if (animated) {
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:ANIMATION_DURATION];
    }
    
    self.alpha = VIEW_ALPHA;
    
    if (animated) {
        [UIView commitAnimations];
    }
}

- (void)dismissAnimated:(BOOL)animated {
    if (animated) {
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:ANIMATION_DURATION];
        [UIView setAnimationDelegate:self];
        [UIView setAnimationDidStopSelector:@selector(didFinishLoadingAnimation)];
    }
    
    self.alpha = 0;
    if (!animated) {
        [self removeFromSuperview];
    }
    
    if (animated) {
        [UIView commitAnimations];
    }
}

- (void)dismiss {
    [self dismissAnimated:YES];
}

- (void)didFinishLoadingAnimation {
    [self removeFromSuperview];
}

- (void)layoutSubviews {
    [super layoutSubviews];
    spinning.center = CGPointMake(self.frame.size.width / 2, self.frame.size.height / 2);
}

- (void)dealloc {
    [spinning release];
    
    [super dealloc];
}

@end
